// 观察者模式
class Observe {
    constructor() {
        this.eventObj = {}
    }
    // 订阅事件
    eventDep(eventName, cb) {
        if (typeof (this.eventObj[eventName]) === "undefined")
            this.eventObj[eventName] = []
        this.eventObj[eventName].push(cb)
    }
    // 发布事件
    trigger(eventName, ...args) {
        if (typeof (this.eventObj[eventName]) !== "undefined")
            this.eventObj[eventName].forEach(item => item(...args))
    }
    // 取消订阅
    unsubscribe(eventName) {
        if (typeof (this.eventObj[eventName]) !== "undefined")
            this.eventObj[eventName] = null
    }
}


// 创建移动的小球
class Ball {
    constructor() {
        // 用来对观察者进行计数
        this.count = 1
        // 创建小球
        this.createBall()
        // 创建观察者
        this.event = new Observe()
    }
    // 创建小球
    createBall() {
        this.ball = document.createElement('div')
        this.ball.style = `background:${this.createColor()};width:100px;height:100px;position:absolute;left:0;top:0;border-radius:50%;`
        document.body.appendChild(this.ball)
    }
    // 给小球分配任意颜色
    createColor() {
        this.color = ''
        for (let i = 0; i < 3; i++) {
            this.color += `${Math.floor(Math.random()*256)} ,`
        }
        this.color = `rgb(${this.color.slice(0,-1)})`
        return this.color
    }
    // 小球的移动
    move(dir, end) {
        this.timer = setInterval(() => {
            this.current = parseInt(getComputedStyle(this.ball)[dir])
            this.speed = 50 * (end > this.current ? 1 : -1)
            if (this.current === end) {
                clearInterval(this.timer)
                // 触发观察者
                this.event.trigger('event' + this.count)
                this.count++
            } else {
                this.ball.style[dir] = this.current + this.speed + 'px'
            }
        }, 300)
    }
}

export {
    Observe,
    Ball
}